<template>
  <div>
    
    <p v-if="broId" class="title">编辑广播</p>

    <p v-else class="title">新建广播</p>
    <div>
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item prop="broName" label="广播名称：">
          <el-input v-model="form.broName" size="small"></el-input>
        </el-form-item>
        <el-form-item prop="broName" label="广播类型：">
          <el-select v-model="form.btId" size="small" placeholder="请选择类型">
            <el-option v-for="item in typeList" :key="item.btId" :label="item.btName" :value="item.btId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="broName" label="排序：">
          <el-input v-model="form.orders" size="small"></el-input>
        </el-form-item>
        <!-- 上传封面 -->
        <el-form-item prop="broName" label="上传封面：">
          <UploadImg :limit="1" :imgUrl="form.cover" @uploadImg="uploadImg"></UploadImg>
        </el-form-item>

        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="简介" name="first">
            <!-- 富文本简介 -->
            <el-form-item prop="intro" label-width="0">
              <RichText :content="form.intro" @onEditorChange="onEditorChange" />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane v-if="broId" label="目录" name="second">

            <el-button class="add" @click="add" type="primary" icon="el-icon-plus">添加音频</el-button>
            <el-table v-loading="loading" element-loading-text="音频上传中" element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)" :data="catalogueList" border>
              <el-table-column  label=" 名称" align="center">
                <template slot-scope="scope">

                  <el-input v-if="scope.row.isEdit==1" v-model="scope.row.catName" size="small"></el-input>
                  <span v-else>{{scope.row.catName}}</span>
                </template>
              </el-table-column>
              <el-table-column  label="音频" align="center">
                <template slot-scope="scope">
                  <label v-if="scope.row.isEdit==1" for="inputId" icon="el-icon-plus">
                    <span v-if="scope.row.audio">重新上传</span>
                    <span v-else>上传音频</span>
                    <input style="display: none" id="inputId" ref="input" type="file"
                      @change="uploadAudio($event,scope.$index)" />
                  </label>

                  <span v-if="scope.row.isEdit==0&&scope.row.audio">已上传</span>

                </template>
              </el-table-column>
              <el-table-column  label="作者" align="center">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEdit==1" v-model="scope.row.author" size="small"></el-input>
                  <span v-else>{{scope.row.author}}</span>
                </template>
              </el-table-column>
              <el-table-column label="排序" align="center">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEdit==1" v-model="scope.row.orders" size="small"></el-input>
                  <span v-else>{{scope.row.orders}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.isEdit==0" @click="edit(scope.$index)" type="primary" size="small">编辑
                  </el-button>
                  <el-button v-else-if="scope.row.isEdit==1" @click="save(scope.row,scope.$index)" type="primary"
                    size="small">保存
                  </el-button>
                  <el-button @click="deleteCatalogue(scope.row.catId)" type="primary" size="small">删除</el-button>
                </template>

              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <el-form-item>
          <el-button type="primary" @click="$router.go(-1)">返回</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
  import RichText from "@/components/RichText.vue";
  import UploadImg from "@/components/UploadImg.vue"
  import apis from "@/apis/modules/radio";
  export default {
    components: {
      RichText,
      UploadImg
    },
    data() {
      return {
        broId: "",//广播id
        typeList: [],//广播类型列表
        catalogueList: [],//目录列表
        loading: false,
        //音频上传
        fileList: [],
        //音频数据
        tableData: [],
        //简介目录默认激活
        activeName: "first",
        //富文本组件传值
        isClear: false,
        detail: "",
        //表单默认值
        imageUrl: "",
        form: {
          broName: "",//	广播名称
          btId: "",//	广播类型id
          cover: "",//	封面
          intro: "",//	简介
          orders: "",//	排序
        },
        rules: {
          broName: [{ required: true, message: '请输入广播名称', trigger: 'blur' }],
          btId: [{ required: true, message: '请选择广播类型', trigger: 'change' }],
          orders: [{ required: true, message: '请输入排序', trigger: 'blur' }],
          cover: [{ required: true, message: '请输入上传封面', trigger: 'blur' }],
          intro: [{ required: true, message: '请输入输入广播简介', trigger: 'blur' }],
        },
        row: {},
      };
    },
    mounted() {
      this.broId = this.$route.query.broId;
      if (this.broId) {
        this.showBroadcast()
      }
      this.getAllBroadcastType()
    },
    methods: {
      // 查询广播详情
      async showBroadcast() {
        const { code, data, msg } = await apis.showBroadcast({
          broId: this.broId
        })
        if (code == 200) {
          this.form = {
            broId: data.broId,
            broName: data.broName,
            btId: data.btId,
            cover: data.cover,
            intro: data.intro,
            orders: data.orders,
          }
        }
      },

      // 获取目录
      async getCatalogue() {
        const { code, data, msg } = await apis.getCatalogue({
          broId: this.broId
        })
        if (code == 200) {
          this.catalogueList = data.map(item => {
            item.isEdit = 0;
            return item
          })

        }
      },
      // 获取全部广播类型
      async getAllBroadcastType() {
        const { code, data, msg } = await apis.getAllBroadcastType()
        if (code == 200) {
          this.typeList = data;
        }
      },
      // 添加广播
      add() {
        this.catalogueList.push({
          catName: "",//	名称
          audio: "",//	音频
          duration: "",//	时长
          author: "",//	作者
          orders: 0,//	排序
          isEdit: 1
        })
      },
      // 编辑
      edit(index) {
        this.catalogueList[index].isEdit = 1;
      },
      // 上传音频
      async uploadAudio(e, index) {
        let file = e.target.files[0];
        let formdata = new FormData();
        formdata.append("myfile", file);
        this.loading = true;
        const { code, data, msg } = await apis.uploadAudio(formdata)
        if (code == 200) {
          this.loading = false;
          var audioElement = new Audio(data);
          audioElement.addEventListener("loadedmetadata", (_event) => {
            this.catalogueList[index].duration = this.formateSeconds(audioElement.duration);
          });
          this.catalogueList[index].audio = data;
        }
      },
      //将秒转化为时分秒
      formateSeconds(endTime) {
        let secondTime = parseInt(endTime)//将传入的秒的值转化为Number
        let min = 0// 初始化分
        let h = 0// 初始化小时
        let result = ''
        if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
          min = parseInt(secondTime / 60)//获取分钟，除以60取整数，得到整数分钟
          secondTime = parseInt(secondTime % 60)//获取秒数，秒数取佘，得到整数秒数
          if (min > 60) {//如果分钟大于60，将分钟转换成小时
            h = parseInt(min / 60)//获取小时，获取分钟除以60，得到整数小时
            min = parseInt(min % 60) //获取小时后取佘的分，获取分钟除以60取佘的分
          }
        }
        result = `${h.toString().padStart(2, '0')}:${min.toString().padStart(2, '0')}:${secondTime.toString().padStart(2, '0')}`
        return result
      },
      // 保存
      async save(row, index) {
        if (row.catName == "") {
          this.$message.error("请输入目录名称")
          return false
        }
        if (row.catName == "") {
          this.$message.error("请上传音频")
          return false
        }
        if (row.catName == "") {
          this.$message.error("请输入作者")
          return false
        }
        if (row.catName == "") {
          this.$message.error("请输入排序")
          return false
        }
        if (row.catId) {
          // 修改目录
          const { code, data, msg } = await apis.updateCatalogue({
            catId: row.catId,
            catName: row.catName,//	名称
            audio: row.audio,//	音频
            duration: row.duration,//	时长
            author: row.author,//	作者
            orders: row.orders,//	排序
          })
          if (code == 200) {
        
            this.catalogueList[index].isEdit = 0

            this.$message.success(msg)
          }
        } else {
          const { code, data, msg } = await apis.insertCatalogue({
            broId: this.broId,
            catName: row.catName,//	名称
            audio: row.audio,//	音频
            duration: row.duration,//	时长
            author: row.author,//	作者
            orders: row.orders,//	排序
          })
          if (code == 200) {
            this.getCatalogue()
            this.$message.success(msg)

          }
        }

      },
      deleteCatalogue(catId) {
        this.$confirm('确认删除该目录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { code, data, msg } = await apis.deleteCatalogue({
            catId
          })
          if (code == 200) {
            this.getCatalogue()
            this.$message.success(msg)
          }
        }).catch(() => {

        });

      },
      // 获取图片
      uploadImg(e) {
        this.form.cover = e.join(',');
      },
      // 获取富文本编辑器内容
      onEditorChange(content) {
        this.form.intro = content;
      },
      // tab切换
      handleClick(tab, event) {
        if (tab.index == 0) {
          this.showBroadcast()
        } else {
          this.getCatalogue()
        }
      },
      //提交表单
      submit() {
        console.log(this.form)
        this.$refs.form.validate(async valid => {
          if (valid) {
            if (this.broId) {
              // 添加广播
              const { code, data, msg } = await apis.updateBroadcast(this.form)
              if (code == 200) {
                this.$message.success(msg)
              } else {
                this.$message.error(msg)
              }
            } else {
              // 修改广播
              const { code, data, msg } = await apis.insertBroadcast(this.form)
              if (code == 200) {
                this.$message.success(msg)
              } else {
                this.$message.error(msg)
              }
            }
          }
        })
      },
    },
  };
</script>

<style lang="scss" scoped>
  .title {
    margin-bottom: 32px;
  }

  .el-input,
  .el-select {
    width: 300px;
  }

  .add {
    margin-bottom: 16px;
  }

  .cell .upload-demo {
    margin-top: 0;
  }

  /* 
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  } */

  .el-tabs {
    margin-bottom: 50px;
  }

  .upload-demo {
    margin-top: 20px;
  }
</style>